import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;
import java.util.HashMap;
import java.util.Map;

public class UdpServer {
    Map<String,String> dict = new HashMap<>();
    DatagramSocket socket = null;
    public UdpServer(int port) throws SocketException {
        socket = new DatagramSocket(port);
        dict.put("小狗","dog");
        dict.put("小猫","cat");
        dict.put("小猪","pig");
        dict.put("小羊","sheep");
    }
    public void start() throws IOException {
        System.out.println("服务器启动!");
        while (true){
            DatagramPacket requestPacket = new DatagramPacket(new byte[4096],4096);
            socket.receive(requestPacket);
            String request = new String(requestPacket.getData(),0,requestPacket.getLength());
            String respond = process(request);
            DatagramPacket respondPacket = new DatagramPacket(respond.getBytes(),respond.getBytes().length,requestPacket.getSocketAddress());
            socket.send(respondPacket);
            System.out.printf("[%s:%d] req=%s resp=%s\n",requestPacket.getSocketAddress(),requestPacket.getPort(),request,respond);
        }
    }

    private String process(String request) {
        return dict.getOrDefault(request,"未找到该单词");
    }

    public static void main(String[] args) throws IOException {
        UdpServer udpserver = new UdpServer(8888);
        udpserver.start();
    }
}
